package com.example.springboot159.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * @author Yangxq
 * @version 2016年1月25日 上午9:39:09 加密解密工具类
 * 
 */
@SuppressWarnings("restriction")
public class AESEncodeUtil {

	private static final Logger logger = LoggerFactory.getLogger(AESEncodeUtil.class);

	private static Properties prop = new Properties();
	private static final String DefaultKey = "mochasoft1qa2ws3ed!@#$%^";

	/**
	 * 将base 64 code AES解密
	 * 
	 * @param contentString
	 *            待解密的base 64 code
	 * @param keyString
	 *            解密密钥
	 * @return 解密后的string
	 * @throws Exception
	 */
	public static String aesDecrypt(String contentString, String keyString) {
		String decryptString = "404";
		try {
			if (!"".equals(contentString) && !"".equals(keyString)) {
				decryptString = aesDecryptByBytes(base64Decode(contentString), keyString);
			}
		} catch (Exception e) {
			logger.info("数据异常"+e);
			if (e instanceof javax.crypto.BadPaddingException) {
				return "404";
			}
		}
		return decryptString;
	}

	/**
	 * AES解密
	 * 
	 * @param encryptBytes
	 *            待解密的byte[]
	 * @param decryptKey
	 *            解密密钥
	 * @return 解密后的String
	 * @throws Exception
	 */
	public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception { //NOSONAR
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		random.setSeed(decryptKey.getBytes());
		kgen.init(128, random);

		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));
		byte[] decryptBytes = cipher.doFinal(encryptBytes);
		return new String(decryptBytes);
	}

	/**
	 * base 64 decode
	 * 
	 * @param base64Code
	 *            待解码的base 64 code
	 * @return 解码后的byte[]
	 * @throws Exception
	 */
	@SuppressWarnings("restriction")
	public static byte[] base64Decode(String base64Code) throws Exception { //NOSONAR
		return "".equals(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
	}

	/**
	 * AES加密为base 64 code
	 * 
	 * @param contentString
	 *            待加密的内容
	 * @param keyString
	 *            加密密钥
	 * @return 加密后的base 64 code
	 * @throws Exception
	 */
	public static String aesEncrypt(String contentString, String keyString) throws Exception { //NOSONAR
		return base64Encode(aesEncryptToBytes(contentString, keyString));
	}

	/**
	 * base 64 encode
	 * 
	 * @param bytes
	 *            待编码的byte[]
	 * @return 编码后的base 64 code
	 */
	@SuppressWarnings("restriction")
	public static String base64Encode(Object bytes) {
		return new BASE64Encoder().encode((byte[]) bytes);
	}

	/**
	 * AES加密
	 * 
	 * @param content
	 *            待加密的内容
	 * @param encryptKey
	 *            加密密钥
	 * @return 加密后的byte[]
	 * @throws Exception
	 * @throws Exception
	 */
	public static Object aesEncryptToBytes(String content, String encryptKey) throws Exception { //NOSONAR
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		random.setSeed(encryptKey.getBytes());
		kgen.init(128, random);
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(kgen.generateKey().getEncoded(), "AES"));

		return cipher.doFinal(content.getBytes("utf-8"));
	}

	/**
	 * 结合base64实现md5加密
	 * 
	 * @param msg
	 *            待加密字符串
	 * @return 获取md5后转为base64
	 * @throws Exception
	 */
	public static String md5Encrypt(String msg) throws Exception { //NOSONAR
		return "".equals(msg) ? null : base64Encode(md5(msg.getBytes()));
	}

	/**
	 * 获取byte[]的md5值
	 * 
	 * @param bytes
	 *            byte[]
	 * @return md5
	 * @throws Exception
	 */
	public static byte[] md5(byte[] bytes) throws Exception { //NOSONAR
		MessageDigest md = MessageDigest.getInstance("MD5");
		md.update(bytes);

		return md.digest();
	}

	public static void main(String[] args) throws Exception { //NOSONAR


		String userId = "admin";
		String userName = "admin";
		String userPhone = "13598850787";
		String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());



		String var = userId+"+"+userName+"+"+userPhone+"+"+time;
		String result = aesEncrypt(var,DefaultKey);
		System.out.println("加密后明文u：" + result);

		String admin = aesEncrypt("userPhone",DefaultKey);
		System.out.println("admin：" + admin);

/*		String secret = "DunBTojZkghoc2Yzg0VSqg==";
		String secret = "wx2e7288fdd5f458b7";
		System.out.println("解密后明文u：" + aesEncrypt(secret,DefaultKey));*/

	}

}
